<?php
/**
 * @ClassName: Equipment
 * @Description: TODO
 * @author: ynbjykj
 * @Date: 2025-11-27 13:32
 * @Version: V1.0.0
 */

namespace app\api\controller\agent;

use app\api\controller\Api;
use app\common\enum\RackEnum;
use app\common\logic\EquipmentLogic;
use app\common\model;
use think\Db;

class Equipment extends Api
{
    /**
     * 统计数据
     * @return \think\response\Json
     */
    function index()
    {
        $total = 0;
        $unallocated_num = 0;
        $allocated_num = 0;
        $installed_num = 0;
        $notinstalled_num = 0;

        $where = [];
        $center = model\OperationCenter::where('agent_id', $this->user_id)->find();
        if ($center) {
            $where[] = ['center_id', '=', $center['id']];

            $total = model\Equipment::where($where)->count();//总数
            $unallocated_num = model\Equipment::where($where)->where('holder_type', '=', model\Equipment::holder_type_center)->where('h_related_id', '=', $center['id'])->count();//未划拨
            $allocated_num = model\Equipment::where($where)->where('holder_type', '<>', model\Equipment::holder_type_center)->count();//已划拨
            $installed_num = model\Equipment::where($where)->where('holder_type', '<>', model\Equipment::holder_type_center)->where('status', RackEnum::status_used)->count();//已安装
            $notinstalled_num = model\Equipment::where($where)->where('holder_type', '<>', model\Equipment::holder_type_center)->where('status', RackEnum::status_unused)->count();//未安装
        }

        $result = [
            'total' => $total,
            'unallocated_num' => $unallocated_num,
            'allocated_num' => $allocated_num,
            'installed_num' => $installed_num,
            'notinstalled_num' => $notinstalled_num,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    /**
     * 设备列表
     * @return \think\response\Json
     */
    function list()
    {
        $current = input('current', 0);
        $device_type = input('device_type', 0);
        $device_model = input('device_model', 0);
        $holder_type = input('holder_type', 0);
        $sales_method = input('sales_method', 0);
        $skip = input('skip', 0);
        $limit = input('limit', 10);

        $where = [];
        $list = [];

        $center = model\OperationCenter::where('agent_id', $this->user_id)->find();
        if ($center) {
            $where[] = ['center_id', '=', $center['id']];

            if ($device_type) {
                $where[] = ['device_type', '=', $device_type];
            }

            if ($device_model) {
                $where[] = ['grids_num', '=', $device_model];
            }

            if ($holder_type) {
                $where[] = ['holder_type', '=', $holder_type];
            }

            if ($sales_method) {
                $where[] = ['sales_method', '=', $sales_method];
            }

            switch ($current) {
                case 1:
                    //已划拨
                    $where[] = ['holder_type', '<>', model\Equipment::holder_type_center];
//                    $where[] = ['h_related_id', '<>', $center['id']];
                    break;
                case 2:
                    //已安装
                    $where[] = ['holder_type', '<>', model\Equipment::holder_type_center];
                    $where[] = ['status', '=', RackEnum::status_used];
                    break;
                case 3:
                    //未安装
                    $where[] = ['holder_type', '<>', model\Equipment::holder_type_center];
                    $where[] = ['status', '=', RackEnum::status_unused];
                    break;
                default:
                    //未划拨
                    $where[] = ['holder_type', '=', model\Equipment::holder_type_center];
                    $where[] = ['h_related_id', '=', $center['id']];
                    break;
            }
            $list = model\Equipment::where($where)->limit($skip, $limit)->select();
        }

        foreach ($list as $key => &$item) {
            $item['amount'] = bcadd($item['rent'], $item['additional_amount'], 2);
        }

        $result = [
            'list' => $list,
            'is_more' => count($list) >= $limit,
        ];

        return json(["code" => 1, "msg" => "获取成功", "data" => $result]);
    }

    /**
     * 设备划拨
     * @return \think\response\Json
     */
    function allocate()
    {
        $holder_type = input('holder_type', 3);
        $agent_id = input('agent_id', 0);
        $store_id = input('store_id', 0);
        $device_ids = input('device_ids', []);

        $data = [
            'holder_type' => $holder_type
        ];
        if ($holder_type == model\Equipment::holder_type_agent) {
            $data['h_related_id'] = $agent_id;
        } elseif ($holder_type == model\Equipment::holder_type_store) {
            $data['h_related_id'] = $store_id;
        } else {
            $data['h_related_id'] = 0;
        }

        $count = 0;
        foreach ($device_ids as $id) {
            $device = model\Equipment::where('id', $id)->find();
            $op_related_id = 0;
            if ($device) {
                $op_related_id = $device['center_id'];
            }
            $res = model\Equipment::where('id', $id)->update($data);
            if ($res) {
                //添加划拨记录
                EquipmentLogic::addTransferRecords($id, 2, $op_related_id, $data['holder_type'], $data['h_related_id'], '设备划拨');
                $count++;
            }
        }

        return json(['code' => 1, 'msg' => '划拨成功 ' . $count . ' 设备']);
    }

    /**
     * 设备信息
     * @return \think\response\Json
     */
    function getDeviceInfo()
    {
        $device_ids = input('device_ids');

        $list = model\Equipment::where('id', 'in', $device_ids)->distinct('id')
            ->fieldRaw('grids_num,device_type,rent,additional_amount,holder_type,h_related_id,use_type,u_related_id')
            ->group('grids_num')->select();

        return json(['code' => 1, 'msg' => 'ok', 'data' => $list]);
    }

    /**
     * 设备改价/分成配置
     * @return \think\response\Json
     */
    function changePrice()
    {
        $data = input();

        $agent_list = [[
            'agent_id' => $this->user_id,
            'allocation_ratio' => $data['allocation_ratio'],
        ], [
            'agent_id' => $data['agent_id1'],
            'allocation_ratio' => $data['allocation_ratio1'],
        ], [
            'agent_id' => $data['agent_id2'],
            'allocation_ratio' => $data['allocation_ratio2'],
        ], [
            'agent_id' => $data['agent_id3'],
            'allocation_ratio' => $data['allocation_ratio3'],
        ]];

        try {
            foreach ($data['device_ids'] as $id) {
                $device = model\Equipment::get($id);
                if (!$device) {
                    continue;
                }

                $device_data = [
                    'update_time' => date_now(),
                ];

                switch ($device['grids_num']) {
                    case 3:
                        //3#水架
                        $device_data['additional_amount'] = $data['additional_amount3'];
                        break;
                    case 6:
                        //6#水架
                        $device_data['additional_amount'] = $data['additional_amount6'];
                        break;
                    case 9:
                        //9#水架
                        $device_data['additional_amount'] = $data['additional_amount9'];
                        break;
                    case 12:
                        //12#水架
                        $device_data['additional_amount'] = $data['additional_amount12'];
                        break;
                    default:
                        //其他
                        $device_data['additional_amount'] = $data['additional_amount'];
                        break;
                }

                //更新金额
                $res = model\Equipment::where('id', $id)->update($device_data);
                if ($res) {
                    foreach ($agent_list as $item) {
                        if ($item['agent_id']) {
                            //添加分成记录
                            $record = Db::name('equipment_allocation_ratio')->where('device_id', $id)->where('agent_id', $item['agent_id'])->find();
                            if ($record) {
                                //更新分配比例
                                $res1 = Db::name('equipment_allocation_ratio')->where('device_id', $id)->where('agent_id', $item['agent_id'])->update([
                                    'ratio' => $item['allocation_ratio'],
                                    'update_time' => date_now(),
                                ]);
                            } else {
                                //添加分配比例
                                $res1 = Db::name('equipment_allocation_ratio')->insert([
                                    'device_id' => $id,
                                    'agent_id' => $item['agent_id'],
                                    'ratio' => $item['allocation_ratio'],
                                    'create_time' => date_now(),
                                    'update_time' => date_now(),
                                ]);
                            }
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            trace($e);
        }

        return json(['code' => 1, 'msg' => '改价成功']);
    }

    /**
     * 设备绑定客户信息
     * @return \think\response\Json
     */
    function getDeviceCustomer()
    {
        $device_id = input('device_id', 0);

        $info = model\EquipmentCustomer::where('device_id', $device_id)->where('status', RackEnum::status_used)->with(['quipment', 'customer'])->find();

        return json(['code' => 1, 'msg' => 'ok', 'data' => $info]);
    }
}